﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace MainApp
{
    public partial class FrmInputSells_New : DevExpress.XtraEditors.XtraForm
    {
        private OilDB.DataServices data;
        //private List<Product> productList = new List<Product>();
        private List<Product_new> productList = new List<Product_new>();
        private Guid currentStore;
        private OilDB.DataSetOilManagement.IndexForDispensersDataTable newIndex;
        private bool check;

        public FrmInputSells_New(OilDB.DataServices data, Guid currentStore)
        {
            InitializeComponent();
            this.data = data;
            this.currentStore = currentStore;

            //decimal totalExport, totalImport;
            //foreach (OilDB.DataSetOilManagement.ProductsRow row in data.DsOil.Products.Rows)
            //{
            //    totalExport = GetTotalExport(row.ID);
            //    totalImport = GetTotalImport(row.ID);
            //    Product_new tmp = new Product_new(row.ID, row.ProductName, totalImport);
            //    tmp.Dock = DockStyle.Left;
            //    pnlProducts.Controls.Add(tmp);
            //    LoadDispensers(tmp, row.ID);

            //    tmp.ValueChanged += new EventHandler(productDispensers_ValueChanged);
            //    tmp.AddNewClicked += new EventHandler(productDispensers_AddNewClicked);
            //    tmp.DispenserDeleted += new EventHandler(productDispensers_DispenserDeleted);                
            //    productList.Add(tmp);
            //}

            //dateEdit.Validated += new EventHandler(dateEdit_Validated);
            newIndex = new OilDB.DataSetOilManagement.IndexForDispensersDataTable();
            dateEdit.Validating += new CancelEventHandler(dateEdit_Validating);
            dateEdit.EditValueChanged += new EventHandler(dateEdit_EditValueChanged);
            dateEdit.EditValue = DateTime.Now;
            
            this.Width = data.DsOil.Products.Rows.Count * 168;
            this.Load += new EventHandler(FrmInputSells_New_Load);
        }

        void dateEdit_EditValueChanged(object sender, EventArgs e)
        {
            if (dateEdit.DateTime.Date > DateTime.Now.Date)
            {
                dateEdit.EditValue = DateTime.Now;
            }
            check = dateEdit.DateTime.Date == DateTime.Now.Date;
            decimal totalExport, totalImport;
            data.IndexForDispensersAdapter.Fill(data.DsOil.IndexForDispensers, null, dateEdit.DateTime.Date);
            data.IndexForDispensersAdapter.Fill(newIndex, null, dateEdit.DateTime.Date.AddDays(1));            
            data.ImportStatisticsAdapter.Fill(data.DsOil.ImportStatistics, null, dateEdit.DateTime.Date.AddDays(1));
            productList.Clear();
            pnlProducts.Controls.Clear();
            foreach (OilDB.DataSetOilManagement.ProductsRow row in data.DsOil.Products.Rows)
            {
                totalExport = GetTotalExport(row.ID);
                totalImport = GetTotalImport(row.ID);
                //abcxyz
                Product_new tmp = new Product_new(row.ID, row.ProductName, totalImport, check, true, 0);
                tmp.Dock = DockStyle.Left;
                pnlProducts.Controls.Add(tmp);
                LoadDispensers(tmp, row.ID);
                tmp.ValueChanged += new EventHandler(productDispensers_ValueChanged);
                tmp.AddNewClicked += new EventHandler(productDispensers_AddNewClicked);
                tmp.DispenserDeleted += new EventHandler(productDispensers_DispenserDeleted);
                productList.Add(tmp);
            }
        }

        void dateEdit_Validating(object sender, CancelEventArgs e)
        {
            if ((DateTime)dateEdit.EditValue > DateTime.Now)
            {
                e.Cancel = true;
            }
            else
            {
                e.Cancel = false;
            }
        }

        private void LoadDispensers(Product_new product, Guid productid)
        {
            foreach (OilDB.DataSetOilManagement.DispensersRow row in data.DsOil.Dispensers.Rows)
                if ((row.Active || !check) && row.Product == productid && row.StoreID == currentStore)
                {
                    OilDB.DataSetOilManagement.IndexForDispensersRow tmp = data.DsOil.IndexForDispensers.FindByID(row.ID);
                    OilDB.DataSetOilManagement.IndexForDispensersRow tmp2 = newIndex.FindByID(row.ID);
                    product.AddDispenser(row.ID, row.Name, tmp.Index, tmp2.Index);
                }
        }

        private decimal GetTotalImport(Guid product)
        {
            OilDB.DataSetOilManagement.ImportStatisticsRow row = data.DsOil.ImportStatistics.FindByStoreIDProduct(currentStore, product);
            if (row != null)
                return row.TotalAmount;
            else
                return 0;
        }

        //private decimal GetTotalImport(Guid product)
        //{
        //    OilDB.DataSetOilManagement.ImportStatisticsAllRow row = data.DsOil.ImportStatisticsAll.FindByStoreIDProduct(currentStore, product);
        //    if (row != null)
        //        return row.TotalAmount;
        //    else
        //        return 0;
        //}

        private decimal GetTotalExport(Guid product)
        {
            OilDB.DataSetOilManagement.ExportStatisticsAllRow row = data.DsOil.ExportStatisticsAll.FindByProductStoreID(product, currentStore);
            if (row != null)
                return row.TotalAmount;
            else
                return 0;
        }

        #region FormEvents
        void FrmInputSells_New_Load(object sender, EventArgs e)
        {
            dateEdit.EditValue = DateTime.Now;
        }
        
        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            foreach (Product_new product in productList)
            {
                foreach (Dispenser dispenser in product)
                {
                    if (dispenser.ChangedName)
                    {
                        OilDB.DataSetOilManagement.DispensersRow disRow = data.DsOil.Dispensers.FindByID(dispenser.ID);
                        disRow.Name = dispenser.DispenserName;
                    }
                   
                    if (dispenser.TotalInput > 0)
                    {
                        DataRow[] temp = data.DsOil.Sells.Select(String.Format("Dispenser = '{0}' AND (SellTime = '{1}')", dispenser.ID, dateEdit.DateTime.Date));
                        OilDB.DataSetOilManagement.SellsRow editRow;
                        decimal oldAmount;
                        if (temp.Length == 1)
                        {
                            editRow = temp[0] as OilDB.DataSetOilManagement.SellsRow;
                            oldAmount = editRow.Amount;
                        }
                        else if (temp.Length == 0)
                        {
                            //add new row
                            editRow = data.DsOil.Sells.NewSellsRow();
                            editRow.ID = Guid.NewGuid();
                            editRow.SellTime = dateEdit.DateTime.Date;
                            OilDB.DataSetOilManagement.ProductsRow row = data.DsOil.Products.FindByID(product.ProductID);
                            editRow.Price = row.Price;
                            editRow.Commission = row.Commission;
                            editRow.Dispenser = dispenser.ID;
                            oldAmount = 0;
                            editRow.Amount = 0;
                            data.DsOil.Sells.AddSellsRow(editRow);
                        }
                        else
                        {
                            throw new Exception("Duplicate");
                        }
                        editRow.Amount = dispenser.TotalInput;
                       
                        //update export statistics
                        OilDB.DataSetOilManagement.ExportStatisticsAllRow row2 = data.DsOil.ExportStatisticsAll.FindByProductStoreID(product.ProductID, currentStore);
                        if (row2 != null)
                        {
                            row2.TotalAmount += editRow.Amount - oldAmount;
                        }
                        else
                        {
                            data.DsOil.ExportStatisticsAll.AddExportStatisticsAllRow(currentStore, product.ProductID, editRow.Amount - oldAmount);
                        }
                        ////update index for dispenser
                        //OilDB.DataSetOilManagement.IndexForDispensersRow row3 = data.DsOil.IndexForDispensers.FindByID(dispenser.ID);
                        //if (row3 != null)
                        //{
                        //    row3.Index += dispenser.TotalInput;
                        //}
                        //else
                        //{
                        //    data.DsOil.IndexForDispensers.AddIndexForDispensersRow(dispenser.ID, dispenser.TotalInput);
                        //}
                    }
                }
            }
            DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }
        #endregion

        #region ControlEvents
        void productDispensers_ValueChanged(object sender, EventArgs e)
        {
            bool valid = true;
            foreach (Product_new item in productList)
            {
                valid &= item.IsValid;
            }
            btnOK.Enabled = valid;
        }

        void productDispensers_AddNewClicked(object sender, EventArgs e)
        {
            Product_new tmp = sender as Product_new;
            OilDB.DataSetOilManagement.DispensersRow newRow = data.DsOil.Dispensers.NewDispensersRow();
            newRow.ID = Guid.NewGuid();
            newRow.StoreID = currentStore;
            newRow.Product = tmp.ProductID;
            newRow.Name = "Vòi mới";
            //Get new name
            FrmGetName tmpDlg = new FrmGetName(newRow.Name);
            if (tmpDlg.ShowDialog() == DialogResult.OK)
            {
                newRow.Name = tmpDlg.GetName();
            }
            newRow.Active = true;

            FrmGetMeter meterDlg = new FrmGetMeter(0);
            if (meterDlg.ShowDialog() == DialogResult.OK)
            {
                decimal value = meterDlg.GetMeterValue();
                OilDB.DataSetOilManagement.ImportsRow importRow = data.DsOil.Imports.NewImportsRow();
                importRow.ID = newRow.ID;
                importRow.ImportTime = new DateTime(2011, 6, 30);
                importRow.StoreID = newRow.StoreID;
                importRow.Product = newRow.Product;
                importRow.Amount = value;
                importRow.Note = "";
                data.DsOil.Imports.AddImportsRow(importRow);

                OilDB.DataSetOilManagement.SellsRow sellRow = data.DsOil.Sells.NewSellsRow();
                sellRow.ID = newRow.ID;
                sellRow.SellTime = new DateTime(2011, 6, 30);
                sellRow.Amount = value;
                sellRow.Price = 0;
                sellRow.Commission = 0;
                sellRow.Note = "";
                sellRow.Dispenser = newRow.ID;
                data.DsOil.Sells.AddSellsRow(sellRow);
            }
            data.DsOil.Dispensers.AddDispensersRow(newRow);
            tmp.AddDispenser(newRow.ID, newRow.Name);
            data.DsOil.IndexForDispensers.AddIndexForDispensersRow(newRow.ID, 0);
        }

        void productDispensers_DispenserDeleted(object sender, EventArgs e)
        {
            Dispenser dispenser = sender as Dispenser;
            OilDB.DataSetOilManagement.DispensersRow row = data.DsOil.Dispensers.FindByID(dispenser.ID);
            row.Active = false;
        }        
        #endregion
    }
}